var express = require("express");
var router = express.Router();
const usersRouter = require("./users");
var postRouter = require("./post");
var apiRouter = require("./api");
var db = require("../db");
const e = require("connect-flash");
const { ObjectId } = require("bson");
const { Forbidden } = require("http-errors");
const { render } = require("ejs");

/* GET home page. */
router.get("/", async (req, res) => {
  const posts = await db.findPost({});
  res.render("index", {
    title: "一个自由表达的地方",
    ...posts,
  });
});

router.get("/login", (req, res) => {
  res.render("login", {
    title: "欢迎来到登录页面",
  });
});

router.get("/register", (req, res) => {
  res.render("register", {
    title: "注册",
  });
});

router.post("/login", async (req, res) => {
  const { username, password } = req.fields;

  // req.query ?   req.params
  const { callback } = req.query;

  console.log(callback);

  try {
    if (username === "" || password === "") {
      throw new Error("请填写用户名和密码！");
    }
    const result = await db.findOneUser({
      username,
      password,
    });
    if (!result) {
      throw new Error("用户名或者密码错误！");
    }

    // 登陆成功之后，把当前用户信息记录在session中
    delete result.password;
    req.session.user = result;
    req.session.save();

    // 添加flash的提示， 两个参数 提示类型， 提示的信息
    req.flash("success", `欢迎您访问Myblog，${result.username}!`);

    return res.redirect(callback || "/");
  } catch (e) {
    req.flash("error", e.message);
    return res.redirect("back");
  }
});

router.post("/register", async (req, res) => {
  const { username, password, rePassword } = req.fields;

  try {
    if (username === "" || password === "" || rePassword === "") {
      throw new Error("请填写用户名和密码！");
    }
    if (password !== rePassword) {
      throw new Error("两次密码不一致！");
    }

    const tmp = await db.findOneUser({
      username,
    });

    if (tmp) {
      throw new Error("该用户名已注册！");
    }

    const { insertedId: _id } = await db.addOneUser({
      username,
      password,
      sex: "x",
      intro: "",
      avatar: "",
    });

    const user = await db.findOneUser({
      _id,
    });

    user.password && delete user.password;

    req.session.user = user;

    req.flash("success", "您已经成功注册！");
    return res.redirect("/");
  } catch (e) {
    req.flash("error", e.message);
    return res.redirect("back");
  }
});

router.get("/logout", (req, res) => {
  req.session.user = null;

  // 删除当前的session功能
  // req.session.destroy()
  req.flash("success", `您已经正常退出Myblog!`);
  res.redirect("/");
});

module.exports = function (app) {
  app.use("/", router);
  app.use("/user", usersRouter);
  app.use("/post", postRouter);
  app.use("/api", apiRouter);
};
